import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { resetRouteState } from '@/permission'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    avatar: '',
    account: '',

    // 用户信息
    userInfo: {},
    menus: '',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, username) => {
    state.username = username
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  // 新增
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  //登录操作
  async login({ commit }, userInfo) {
    let result = await login(userInfo);

    if (result.code == 200) {
      commit('SET_TOKEN', result.data);
      setToken(result.data);
      return 'ok';
    } else {
      return Promise.reject(new Error(result.msg));
    }
  },

  // 获取用户头像，姓名，角色等信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data, map } = response
        if (!data) {
          return reject('验证失败，请重新登录')
        }
        const { username, avatar } = data
        commit('SET_USERINFO', data);
        commit('SET_NAME', username);
        commit('SET_AVATAR', avatar || '');

        // 处理菜单数据
        if (map) {
          try {
            // // 确保存储的是原始 JavaScript 对象，而不是 Vue 响应式对象
            // const rawMap = JSON.parse(JSON.stringify(map))
            commit('SET_MENUS', map)
          } catch (e) {
            // 直接存储原始数据
            commit('SET_MENUS', map)
          }
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出登录
  logout({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken()
        resetRouter() // 先重置路由
        dispatch('permission/resetRoutes', null, { root: true })
        // 重置标志位
        resetRouteState()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit, dispatch }) {
    return new Promise(resolve => {
      removeToken()
      resetRouter() // 先重置路由
      // 不再调用 resetRouteState
      // 直接调用 permission 模块的 resetRoutes
      dispatch('permission/resetRoutes', null, { root: true })
      // 重置标志位
      resetRouteState()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}